package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private IVoucherOrderService proxy;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        // 1. 创建 RedisScript 对象并设置 Lua 脚本内容及返回类型
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //阻塞队列
    //BlockingQueue这个阻塞队列特点：当一个线程尝试从队列获取元素的时候，如果没有元素该线程阻塞，直到队列中有元素才会被唤醒并获取元素
    //private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024*1024);
    //线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    //类初始化的时候执行线程池
    @PostConstruct
    private void init(){
        try {
            stringRedisTemplate.opsForStream().createGroup("stream.orders", "g1");
        } catch (Exception e) {
            log.info("消费者组 g1 已存在，无需重新创建！");
        }
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWorker.nextId("order");
        //1 执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), String.valueOf(orderId)
        );
        //2 判断结果是否为0
        int result1 = result.intValue();
        if(result1 != 0){
            //3 结果不为0 没有购买资格
            return Result.fail(result1 ==1?"库存不足":"不能重复下单");
        }
        //获取代理对象（事务）
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        //5 返回订单id
        return Result.ok(orderId);
    }

    private class VoucherOrderHandler implements Runnable {
        String queueName = "stream.orders";
        @Override
        public void run() {
            while (true){
                try {
                    //1 获取消息队列中的订单信息
                    //XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),//把消费者组名称和消费者名称传过去
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),//每次读取一条消息，2秒钟拿不到阻塞
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())//从消息队列中读取上次未确认的消息
                    );
                    //2 判断消息是否获取成功
                    if(list == null || list.isEmpty()){
                        //2.1 如果获取失败，说明没有消息，继续下一次循环
                        continue;
                    }
                    //3 如果获取成功
                    // 解析消息中的订单，<String, Object, Object>分别是：
                    // 消息队列名称、消息的唯一标识id、消息内容键值对 Map<Object, Object>，包含具体的订单信息（如 userId、voucherId）。
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> values = record.getValue();
                    //将map集合转成VoucherOrder对象
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    proxy.createVoucherOrder(voucherOrder);//使用代理对象，
                    //4 ACK确认 SACK stream.orders g1 id
                    //告知 Redis，消费者组中某个消费者已经成功处理了这条消息。一旦消息被确认，
                    // 它会从该消费者组的待处理列表（pending-list）中移除。这样可以避免该消息再次被读取或重新投递。
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常",e);
                    handlePendingList();
                }
            }
        }
        //handlePendingList 方法用于处理 pending 列表中的未确认消息。
        private void handlePendingList() {
            while (true){
                try {
                    //1 获取pendingList中的订单信息
                    //XREADGROUP GROUP g1 c1 COUNT 1  STREAMS stream 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),//把组名称和消费者名称传过去
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    //2 判断消息是否获取成功
                    if(list == null || list.isEmpty()){
                        //2.1 如果获取失败，说明pendlist没有消息，跳出当前循环
                        break;
                    }
                    //3 如果获取成功
                    // 解析消息中的订单，
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> values = record.getValue();
                    //将map集合转成VoucherOrder对象
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    proxy.createVoucherOrder(voucherOrder);//使用代理对象，最后用于提交事务
                    //4 ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                } catch (Exception e) {
                    log.error("处理pending-list异常",e);
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        }
    }
    /*private class VoucherOrderHandler implements Runnable {

        @Override
        public void run() {
            while (true){
                try {
                    //获取队列中的信息
                    VoucherOrder voucherOrder = orderTasks.take();
                    //创建订单
                    //handleVoucherOrder(voucherOrder);
                    proxy.createVoucherOrder(voucherOrder);//使用代理对象，最后用于提交事务
                } catch (InterruptedException e) {
                    log.error("处理订单异常",e);
                }
            }
        }
    }*/




    /*@Override
    public Result seckillVoucher(Long voucherId) {
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        //1 执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );
        //2 判断结果是否为0
        int result1 = result.intValue();
        if(result1 != 0){
            //3 结果不为0 没有购买资格
            return Result.fail(result1 ==1?"库存不足":"不能重复下单");
        }
        //4  有购买资格，把下单信息保存到阻塞队列中
        // 创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        // 订单id就是全局唯一id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        //放入阻塞队列中
        orderTasks.add(voucherOrder);
        //获取代理对象（事务）
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        //5 返回订单id
        return Result.ok(orderId);
    }*/

    /**
     * 创建优惠劵订单
     *
     * @param voucherOrder
     */
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //5.1 一人一单
        Long voucherId = voucherOrder.getVoucherId();
        //5.2 查询订单
        int count = query()
                .eq("voucher_id", voucherId)
                .eq("user_id", voucherOrder.getUserId())
                .count();
        if (count > 0) {
            //5.3 判断订单是否存在
            log.error("用户已经购买过一次了");
        }
        //5.4  扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId) //where id = ? and stock > 0
                .gt("stock", 0)
                .update();
        if (!success) {
            log.error("秒杀优惠卷库存不足");
        }
        save(voucherOrder);
    }


    /*@Override
    public Result seckillVoucher(Long voucherId) {
        //1 查询优惠卷
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        //2 判断秒杀是否开始
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            //活动还没开始
            return Result.fail("秒杀活动还没开始");
        }
        //3 判断秒杀是否结束
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            //活动还没开始
            return Result.fail("秒杀活动已经结束");
        }
        //4 判断库存是否充足
        if (voucher.getStock() < 1) {
            return Result.fail("秒杀优惠卷库存不足");
        }

        //7 返回订单id
        //应该先事务提交，在释放锁，不然你先释放锁，当前事务还没提交，导致别的线程进来修改数据库，那坏了
        Long user_id = UserHolder.getUser().getId();

        //尝试去创建锁对象，在获取锁
        RLock lock = redissonClient.getLock("lock:order:" + user_id);
        boolean islock = lock.tryLock();
        if (!islock) {
            return Result.fail("一个人只允许下一单");
        }
        try {
            //获取代理对象（事务）
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } finally {
            //释放锁
            lock.unlock();
        }
    }*/


}
